import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Typography, 
  Table, 
  Button, 
  Space, 
  Input, 
  Modal, 
  Form, 
  Message 
} from '@arco-design/web-react';
import { IconPlus, IconSearch, IconEdit, IconDelete } from '@arco-design/web-react/icon';
import { useTranslation } from 'react-i18next';
import './UserManagement.css';

const { Title } = Typography;

interface User {
  id: string;
  name: string;
  email: string;
  role: string;
  status: 'active' | 'inactive';
  createdAt: string;
}

const UserManagement: React.FC = () => {
  const { t } = useTranslation();
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');

  // 模拟获取用户数据
  useEffect(() => {
    const fetchUsers = () => {
      setLoading(true);
      // 模拟API调用
      setTimeout(() => {
        const mockUsers: User[] = [
          {
            id: '1',
            name: '张三',
            email: 'zhangsan@example.com',
            role: '管理员',
            status: 'active',
            createdAt: '2023-01-15'
          },
          {
            id: '2',
            name: '李四',
            email: 'lisi@example.com',
            role: '编辑者',
            status: 'active',
            createdAt: '2023-02-20'
          },
          {
            id: '3',
            name: '王五',
            email: 'wangwu@example.com',
            role: '查看者',
            status: 'inactive',
            createdAt: '2023-03-10'
          }
        ];
        setUsers(mockUsers);
        setLoading(false);
      }, 1000);
    };

    fetchUsers();
  }, []);

  const handleAddUser = () => {
    form.resetFields();
    setVisible(true);
  };

  const handleEditUser = (user: User) => {
    form.setFieldsValue(user);
    setVisible(true);
  };

  const handleDeleteUser = (id: string) => {
    Modal.confirm({
      title: t('userManagement.deleteConfirm'),
      content: t('userManagement.deleteConfirmContent'),
      onOk: () => {
        setUsers(users.filter(user => user.id !== id));
        Message.success(t('userManagement.deleteSuccess'));
      }
    });
  };

  const handleSubmit = (values: any) => {
    if (values.id) {
      // 编辑用户
      setUsers(users.map(user => user.id === values.id ? { ...user, ...values } : user));
      Message.success(t('userManagement.updateSuccess'));
    } else {
      // 添加用户
      const newUser: User = {
        ...values,
        id: `${users.length + 1}`,
        createdAt: new Date().toISOString().split('T')[0]
      };
      setUsers([...users, newUser]);
      Message.success(t('userManagement.addSuccess'));
    }
    setVisible(false);
  };

  const filteredUsers = users.filter(user => 
    user.name.toLowerCase().includes(searchText.toLowerCase()) ||
    user.email.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns = [
    {
      title: t('userManagement.name'),
      dataIndex: 'name',
    },
    {
      title: t('userManagement.email'),
      dataIndex: 'email',
    },
    {
      title: t('userManagement.role'),
      dataIndex: 'role',
    },
    {
      title: t('userManagement.status'),
      dataIndex: 'status',
      render: (status: 'active' | 'inactive') => (
        <span className={`status-badge ${status}`}>
          {status === 'active' ? t('userManagement.active') : t('userManagement.inactive')}
        </span>
      ),
    },
    {
      title: t('userManagement.createdAt'),
      dataIndex: 'createdAt',
    },
    {
      title: t('userManagement.actions'),
      dataIndex: 'id',
      render: (_: any, record: User) => (
        <Space>
          <Button 
            type="text" 
            size="small" 
            icon={<IconEdit />} 
            onClick={() => handleEditUser(record)}
          >
            {t('userManagement.edit')}
          </Button>
          <Button 
            type="text" 
            size="small" 
            status="danger" 
            icon={<IconDelete />} 
            onClick={() => handleDeleteUser(record.id)}
          >
            {t('userManagement.delete')}
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="user-management-page">
      <div className="page-header">
        <Title heading={3}>{t('menu.userManagement')}</Title>
        <Button type="primary" icon={<IconPlus />} onClick={handleAddUser}>
          {t('userManagement.addUser')}
        </Button>
      </div>

      <Card className="user-list-card">
        <div className="card-header">
          <Input
            prefix={<IconSearch />}
            placeholder={t('userManagement.searchPlaceholder')}
            value={searchText}
            onChange={(value: string) => setSearchText(value)}
            style={{ width: 300 }}
          />
        </div>

        <Table 
          columns={columns}
          data={filteredUsers} 
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title={form.getFieldValue('id') ? t('userManagement.editUser') : t('userManagement.addUser')}
        visible={visible}
        onOk={() => form.submit()}
        onCancel={() => setVisible(false)}
        autoFocus={false}
        focusLock={true}
      >
        <Form form={form} onSubmit={handleSubmit} layout="vertical">
          <Form.Item field="id" hidden>
            <Input />
          </Form.Item>
          <Form.Item 
            field="name" 
            label={t('userManagement.name')}
            rules={[{ required: true, message: t('userManagement.nameRequired') }]}
          >
            <Input placeholder={t('userManagement.namePlaceholder')} />
          </Form.Item>
          <Form.Item 
            field="email" 
            label={t('userManagement.email')}
            rules={[
              { required: true, message: t('userManagement.emailRequired') },
              { type: 'email', message: t('userManagement.emailInvalid') }
            ]}
          >
            <Input placeholder={t('userManagement.emailPlaceholder')} />
          </Form.Item>
          <Form.Item 
            field="role" 
            label={t('userManagement.role')}
            rules={[{ required: true, message: t('userManagement.roleRequired') }]}
          >
            <Input placeholder={t('userManagement.rolePlaceholder')} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;